package com.dupengcheng.wx.controller;

import com.dupengcheng.wx.constant.CommConst;
import com.dupengcheng.wx.entity.WXMessageTypeFactory;
import com.dupengcheng.wx.entity.WXMessageTypeHandler;
import com.dupengcheng.wx.util.MessageUtil;
import com.dupengcheng.wx.util.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@Slf4j
public class CallBackController {



    @Resource
    private WXMessageTypeFactory wxMessageTypeFactory;


    @GetMapping("/callBack")
    public String callBack(String signature,String timestamp,
                           String nonce,String  echostr){

        log.info("signature:{},timestamp:{},nonce:{},echostr:{}",signature,timestamp,nonce,echostr);
        String sha1 = SHA1.getSHA1(CommConst.token, timestamp, nonce, "");
        if (signature.equals(sha1)){
            return echostr;
        }
        return "失败！";


    }
    @PostMapping(value = "/callBack", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("signature:{},timestamp:{},nonce:{},echostr:{}",signature,timestamp,nonce,msgSignature);
        log.info("requestBody:{}",requestBody);

        //根据requestBody里面传递来的消息、是有一个MsgType的这个是都会有的、根据这个来判断是事件还是消息。
        //先将requestBody解析成Map。
        Map<String, String> body = MessageUtil.parseXml(requestBody);

        String msgType=body.get("MsgType");
        String event = body.get("Event");

        String type= !StringUtils.isEmpty(event)? Stream.of(msgType, event).collect(Collectors.joining("."))
                :msgType;
        log.info("msgType:{},event:{}",msgType,event);
        WXMessageTypeHandler typeHandlerByType = wxMessageTypeFactory.getTypeHandlerByType(type);
        if (ObjectUtils.isEmpty(typeHandlerByType)){
            return "unknown";
        }
        String replyContent = typeHandlerByType.execute(body);
        log.info("replyContent:{}",replyContent);

        return replyContent;
    }


}
